<template>
    <div ref="chartRef" style="width:98%; height:300px;"></div>
</template>

<script setup>
/**
 * 会员统计折线图
 * 说明：注册人数、活跃人数
 */
import * as echarts from 'echarts';
import { ref, onMounted, inject, watch } from 'vue';

// 获取全局变量
const global = inject('global');
// 声明引用变量
const chartRef = ref(null);
// 声明图表实例
var myChart = null;

// 监听全局变量
watch(global.isDarkTheme, (value) => {
    initChart(value);
})

// 生成模拟数据
const mockData = (isData = true, option = { min: 0, max: 500 }) => {
    let data = [], label = '', value = 0;
    for (let i = 1; i < 32; i++) {
        label = (i < 10 ? '0' : '') + i;
        if (isData) {
            value = option.min + Math.floor(Math.random() * option.max)
            data.push(value);
            continue;
        }
        data.push(label);
    }
    return data;
}

// 生成图表
const initChart = (isDark) => {
    if (myChart) {
        myChart.dispose();
    }
    // 基于准备好的dom，初始化echarts实例
    myChart = echarts.init(chartRef.value, isDark ? 'dark' : 'light');
    // 绘制图表
    var bizData = {
        date: mockData(false),
        data1: mockData(),
        data2: mockData(),
    };

    var option;

    option = {
        title: {
            text: '会员趋势图'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['注册人数', '活跃人数']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
            data: bizData.date,
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '注册人数',
                type: 'line',
                stack: 'Total',
                // data: [120, 132, 101, 134, 90, 230, 210],
                data: bizData.data1,
            },
            {
                name: '活跃人数',
                type: 'line',
                stack: 'Total',
                // data: [220, 182, 191, 234, 290, 330, 310],
                data: bizData.data2,
            },
        ]
    };

    option && myChart.setOption(option);
}

// 视图加载方法
onMounted(() => {
    initChart(global.isDarkTheme.value);
})
</script>